package com.showsu.editor.utils.aliyun.moderaction;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.ImageModerationRequest;
import com.aliyun.green20220302.models.ImageModerationResponse;
import com.aliyun.green20220302.models.ImageModerationResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.showsu.editor.utils.aliyun.BaseAliyunUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.UUID;


/**
 * @Author: jph
 * @Description: 阿里云图片审核增强版工具类
 * @Date: Created in 16:54 下午 2024/06/25
 * @Modified By:
 */
@Slf4j
@Component
public class AliyunImageModerationUtil extends BaseAliyunUtil<Client> {

    @Value("${aliyun.vpc.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.vpc.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.vpc.endpoint}")
    private String endpoint;



    @Override
    public void initClient(String accessKeyId, String accessKeySecret, String endpoint) {
        try {
            this.client= this.createClient(accessKeyId,accessKeySecret,endpoint);
        }catch (Exception e) {
            System.out.println("阿里云图片审核增强版工具类 实例化报错："+e.getMessage());
            throw new RuntimeException(e);
        }
    }
    @PostConstruct
    public void init(){
        System.out.println("开始实例化 阿里云图片审核增强版工具类");
        this.initClient(accessKeyId,accessKeySecret,endpoint);
        System.out.println("结束实例化 阿里云图片审核增强版工具类");
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @param endpoint
     * @return Client
     * @throws Exception
     */
    public Client createClient(String accessKeyId, String accessKeySecret,String endpoint) throws Exception {
        Config config = new Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Mts
        config.setEndpoint(endpoint);
        return new Client(config);
    }
    public ImageModerationResponseBody.ImageModerationResponseBodyData run(Client client, AliyunImageModerationServiceCodeEnum serviceCodeEnum, String imageUrl){
        // ====================== 3. 发起请求） ======================
        ImageModerationResponseBody.ImageModerationResponseBodyData result=null;

        //检测参数构造
        JSONObject serviceParameters = new JSONObject();
        //公网可访问的URL。
        serviceParameters.put("imageUrl", imageUrl);
        //待检测数据唯一标识
        serviceParameters.put("dataId", UUID.randomUUID().toString());

        if (serviceParameters.get("imageUrl") == null || serviceParameters.getString("imageUrl").trim().length() == 0) {
            System.out.println("image moderation imageUrl is empty");
            return result;
        }

        // 创建RuntimeObject实例并设置运行参数
        RuntimeOptions runtime = new RuntimeOptions();
        ImageModerationRequest request = new ImageModerationRequest();
        // 图片检测service：内容安全控制台图片增强版规则配置的serviceCode，示例：baselineCheck
        // 支持service请参考：https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
        request.setService(serviceCodeEnum.getCode());
        request.setServiceParameters(serviceParameters.toJSONString());

        try {
            // 调用方法获取检测结果。
            ImageModerationResponse response = client.imageModerationWithOptions(request, runtime);
            // 自动路由。
            if (response != null) {
                // 服务端错误，区域切换到cn-beijing。
                if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                    // 接入区域和地址请根据实际情况修改。
//                    config.setRegionId("cn-beijing");
//                    config.setEndpoint("green-cip.cn-beijing.aliyuncs.com");
//                    client = new Client(config);
//                    response = client.textModerationWithOptions(textModerationRequest, runtime);
                }
            }
            // 打印检测结果。
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    ImageModerationResponseBody body = response.getBody();
                    Integer code = body.getCode();
                    if (code != null && code == 200) {
                        result = body.getData();
                    } else {
                        log.error("阿里云图片审核增强版工具类 参数:{} image moderation not success. code:{},conteng:{},",serviceCodeEnum.getMsg(),code,imageUrl);
                    }
                } else {
                    log.error("阿里云图片审核增强版工具类 参数:{} response not success. status:{},conteng:{},",serviceCodeEnum.getMsg(),response.getStatusCode(),imageUrl);
                }
            }
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            log.error("阿里云图片审核增强版工具类 参数:{} 报错:{},conteng:{},",serviceCodeEnum.getMsg(),error.getMessage(),imageUrl);
            // 诊断地址
            log.error(error.getData().get("Recommend").toString());
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            log.error("阿里云图片审核增强版工具类 参数:{} 报错:{},conteng:{},",serviceCodeEnum.getMsg(),error.getMessage(),imageUrl);
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return result;
    }

    public ImageModerationResponseBody.ImageModerationResponseBodyData start(Client thisClient, AliyunImageModerationServiceCodeEnum serviceCodeEnum, String imageUrl) {
        return run(thisClient,serviceCodeEnum,imageUrl);
    }

    public ImageModerationResponseBody.ImageModerationResponseBodyData start(String accessKeyId, String accessKeySecret, String endpoint, AliyunImageModerationServiceCodeEnum serviceCodeEnum, String imageUrl) {
        try {
            Client newClient= this.createClient(accessKeyId,accessKeySecret,endpoint);
            return start(newClient,serviceCodeEnum,imageUrl);
        }catch (Exception e) {
            log.error("start方法 阿里云图片审核增强版工具类 实例化报错："+e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public ImageModerationResponseBody.ImageModerationResponseBodyData start(String imageUrl) {
        if(this.client==null){
            return start(accessKeyId,accessKeySecret,endpoint, AliyunImageModerationServiceCodeEnum.baselineCheck_pro,imageUrl);
        }
        return start(this.client, AliyunImageModerationServiceCodeEnum.baselineCheck_pro,imageUrl);
    }
    public ImageModerationResponseBody.ImageModerationResponseBodyData start(AliyunImageModerationServiceCodeEnum serviceCodeEnum, String imageUrl) {
        if(this.client==null){
            return start(accessKeyId,accessKeySecret,endpoint,serviceCodeEnum,imageUrl);
        }
        return start(this.client,serviceCodeEnum,imageUrl);
    }
    public Boolean startGetBoolean(AliyunImageModerationServiceCodeEnum serviceCodeEnum, String imageUrl) {
        ImageModerationResponseBody.ImageModerationResponseBodyData data=null;
        if(this.client==null){
            data=start(accessKeyId,accessKeySecret,endpoint,serviceCodeEnum,imageUrl);
        }else{
            data=start(this.client,serviceCodeEnum,imageUrl);
        }
        List<ImageModerationResponseBody.ImageModerationResponseBodyDataResult> resultList=data.getResult();
        if(resultList.size()>1){
            return true;
        }else if(resultList.size()>0){
            ImageModerationResponseBody.ImageModerationResponseBodyDataResult result=resultList.get(0);
            if(result!=null){
                if(!StringUtils.contains(result.getLabel(),"nonLabel")){
                    return true;
                }
            }
        }
        return false;
    }

    public String startGetString(AliyunImageModerationServiceCodeEnum serviceCodeEnum, String imageUrl) {
        ImageModerationResponseBody.ImageModerationResponseBodyData data=null;
        if(this.client==null){
            data=start(accessKeyId,accessKeySecret,endpoint,serviceCodeEnum,imageUrl);
        }else{
            data=start(this.client,serviceCodeEnum,imageUrl);
        }
        return  data.getRiskLevel();
    }

    public AliyunModerationRiskLevelEnum startGetRiskLevel(AliyunImageModerationServiceCodeEnum serviceCodeEnum, String imageUrl) {
        ImageModerationResponseBody.ImageModerationResponseBodyData data=null;
        if(this.client==null){
            data=start(accessKeyId,accessKeySecret,endpoint,serviceCodeEnum,imageUrl);
        }else{
            data=start(this.client,serviceCodeEnum,imageUrl);
        }
        return  AliyunModerationRiskLevelEnum.getByCode(data.getRiskLevel());
    }

    public ImageModerationResponseBody.ImageModerationResponseBodyData start(String serviceCode,String imageUrl) {
        if(this.client==null){
            return start(accessKeyId,accessKeySecret,endpoint, AliyunImageModerationServiceCodeEnum.getByCode(serviceCode),imageUrl);
        }
        return start(this.client, AliyunImageModerationServiceCodeEnum.getByCode(serviceCode),imageUrl);
    }
}
